package com.ztk.reentrantlock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class ConditionDemo {
    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    private boolean conditionFlag;

    private void await() throws InterruptedException {
        try {
            lock.lock();
            while (!conditionCheck()) {
                System.out.println("准备沉睡!!!");
                condition.await();
                System.out.println("被唤醒了!!!");
            }
        } finally {
            lock.unlock();
        }
    }

    private void signal() {
        try {
            lock.lock();
            changCondition();
            System.out.println("准备唤醒!!!");
            condition.signal();
            System.out.println("唤醒结束!!!");
        } finally {
            lock.unlock();
        }
    }

    private boolean conditionCheck() {
        return conditionFlag;
    }

    private void changCondition() {
        conditionFlag = true;
    }

    public static void main(String[] args) throws InterruptedException {
        ConditionDemo conditionDemo = new ConditionDemo();
        Thread thread = new Thread(() -> {
            try {
                conditionDemo.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        thread.start();
        Thread.sleep(1000L);
        conditionDemo.signal();
    }
}
